package com.example.fanpaiyouxi

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*

class EditInfoActivity : AppCompatActivity() {

    private lateinit var etName: EditText
    private lateinit var rgGender: RadioGroup
    private lateinit var rbMale: RadioButton
    private lateinit var rbFemale: RadioButton
    private lateinit var etPhone: EditText
    private lateinit var btnSave: Button
    private lateinit var btnCancel: Button

    private lateinit var originalInfo: PlayerInfo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_info)

        originalInfo = intent.getParcelableExtra("player_info") ?:
                PlayerInfo(getString(R.string.default_name), getString(R.string.gender_male), getString(R.string.default_phone), 0)

        initViews()
        setupClickListeners()
        displayCurrentInfo()
    }

    private fun initViews() {
        etName = findViewById(R.id.etName)
        rgGender = findViewById(R.id.rgGender)
        rbMale = findViewById(R.id.rbMale)
        rbFemale = findViewById(R.id.rbFemale)
        etPhone = findViewById(R.id.etPhone)
        btnSave = findViewById(R.id.btnSave)
        btnCancel = findViewById(R.id.btnCancel)
    }

    private fun setupClickListeners() {
        btnSave.setOnClickListener {
            saveInfo()
        }

        btnCancel.setOnClickListener {
            finish()
        }
    }

    private fun displayCurrentInfo() {
        etName.setText(originalInfo.name)
        etPhone.setText(originalInfo.phone)

        when (originalInfo.gender) {
            getString(R.string.gender_male) -> rbMale.isChecked = true
            getString(R.string.gender_female) -> rbFemale.isChecked = true
        }
    }

    private fun saveInfo() {
        val name = etName.text.toString().trim()
        val phone = etPhone.text.toString().trim()
        val gender = if (rbMale.isChecked) getString(R.string.gender_male) else getString(R.string.gender_female)

        if (name.isEmpty() || phone.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show()
            return
        }

        val updatedInfo = PlayerInfo(name, gender, phone, originalInfo.highScore)

        val resultIntent = Intent().apply {
            putExtra("updated_info", updatedInfo)
        }
        setResult(RESULT_OK, resultIntent)
        finish()
    }
}